package org.smileface.designpattern.factory.simplefactory;

import java.lang.reflect.Constructor;

/**
 * @description: 简单工厂
 * @author: chujian
 * @since: 2022-02-14 22:24
 **/
public class ColorFactory {

    /**
     * 简单工厂，方式1，通过name获取IColor对象
     *
     * @param name
     * @return
     */
    public IColor createColor(String name) {
        if ("red".equals(name)) {
            return new RedColor();
        } else if ("green".equals(name)) {
            return new GreenColor();
        }

        return null;
    }

    /**
     * 简单工厂，方式2，通过ClassName获取IColor对象
     *
     * @param className
     * @return
     */
    public IColor createColor2(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            Constructor<?> constructor = clazz.getConstructor();
            Object instance = constructor.newInstance();
            return (IColor) instance;
        } catch (Exception e) {
            throw new RuntimeException("class load error: " + className);
        }
    }

    /**
     * 简单工厂，方式3，通过clazz获取对象
     *
     * @param clazz
     * @return
     */
    public IColor createColor3(Class<? extends IColor> clazz) {
        try {
            Constructor<?> constructor = clazz.getConstructor();
            Object instance = constructor.newInstance();
            return (IColor) instance;
        } catch (Exception e) {
            throw new RuntimeException("class load error: " + clazz.getName());
        }
    }

}
